package studentdemo.ui;

import studentdemo.modul.Report;
import studentdemo.modul.Student;
import studentdemo.modul.Course;
import studentdemo.modul.Teacher;
import studentdemo.server.ReportService;
import studentdemo.server.StudentService;
import studentdemo.server.CourseService;
import studentdemo.server.TeacherService;
import studentdemo.server.OfferService;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class ReportPanel extends JPanel {
    private ReportService reportService = new ReportService();
    private StudentService studentService = new StudentService();
    private CourseService courseService = new CourseService();
    private TeacherService teacherService = new TeacherService();
    private OfferService offerService = new OfferService();
    private JComboBox<Student> studentBox;
    private JComboBox<Course> courseBox;
    private JComboBox<Teacher> teacherBox;
    private JComboBox<String> semesterBox;
    private JTextField gradeField;
    private JButton addBtn, editBtn, deleteBtn, refreshBtn;
    private JTable table;
    private DefaultTableModel tableModel;

    public ReportPanel() {
        setLayout(new BorderLayout());
        // 顶部
        JPanel topPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 10, 5));
        studentBox = new JComboBox<>();
        semesterBox = new JComboBox<>();
        courseBox = new JComboBox<>();
        teacherBox = new JComboBox<>();
        refreshBtn = new JButton("刷新");
        topPanel.add(new JLabel("学生:"));
        topPanel.add(studentBox);
        topPanel.add(new JLabel("学期:"));
        topPanel.add(semesterBox);
        topPanel.add(new JLabel("课程:"));
        topPanel.add(courseBox);
        topPanel.add(new JLabel("教师:"));
        topPanel.add(teacherBox);
        topPanel.add(refreshBtn);
        add(topPanel, BorderLayout.NORTH);

        // 底部
        JPanel opPanel = new JPanel();
        gradeField = new JTextField(5);
        addBtn = new JButton("新增成绩");
        editBtn = new JButton("修改成绩");
        deleteBtn = new JButton("删除成绩");
        opPanel.add(new JLabel("成绩:"));
        opPanel.add(gradeField);
        opPanel.add(addBtn);
        opPanel.add(editBtn);
        opPanel.add(deleteBtn);
        add(opPanel, BorderLayout.SOUTH);

        // 表格区
        String[] columns = {"学生编号", "学生姓名", "课程编号", "课程名称", "学期", "成绩", "教师编号", "教师姓名"};
        tableModel = new DefaultTableModel(columns, 0) {
            public boolean isCellEditable(int row, int column) { return false; }
        };
        table = new JTable(tableModel);
        JScrollPane scrollPane = new JScrollPane(table);
        add(scrollPane, BorderLayout.CENTER);

        // 事件绑定
        addBtn.addActionListener(e -> addReportAction());
        editBtn.addActionListener(e -> editReportAction());
        deleteBtn.addActionListener(e -> deleteReportAction());
        refreshBtn.addActionListener(e -> {
            loadStudentBox();
            loadCourseBox();
            loadTeacherBox();
            loadSemesterBox();
            loadTable();
        });
        studentBox.addActionListener(e -> loadTableByStudent());
        semesterBox.addActionListener(e -> {
            String semester = (String) semesterBox.getSelectedItem();
            loadCourseBoxBySemester(semester);
        });
        courseBox.addActionListener(e -> loadTableByCourse());
        teacherBox.addActionListener(e -> loadTableByTeacher());

        loadStudentBox();
        loadSemesterBox();
        String semester = (String) semesterBox.getSelectedItem();
        loadCourseBoxBySemester(semester);
        loadTeacherBox();
        loadTable();
    }

    private void loadStudentBox() {
        studentBox.removeAllItems();
        List<Student> students = studentService.getStudentsByPage(1, 1000);
        for (Student s : students) {
            studentBox.addItem(s);
        }
    }

    private void loadCourseBox() {
        courseBox.removeAllItems();
        List<Course> courses = courseService.getCoursesByPage(1, 1000);
        for (Course c : courses) {
            courseBox.addItem(c);
        }
    }

    private void loadTeacherBox() {
        teacherBox.removeAllItems();
        List<Teacher> teachers = teacherService.getTeachersByPage(1, 1000);
        for (Teacher t : teachers) {
            teacherBox.addItem(t);
        }
    }

    private void loadSemesterBox() {
        semesterBox.removeAllItems();
        Set<String> semesters = new HashSet<>();
        List<Course> courses = courseService.getCoursesByPage(1, 1000);
        for (Course c : courses) {
            semesters.add(c.getSemester());
        }
        List<Report> reports = reportService.getAllReports();
        for (Report r : reports) {
            semesters.add(r.getSemester());
        }
        for (String s : semesters) {
            semesterBox.addItem(s);
        }
    }

    private void loadCourseBoxBySemester(String semester) {
        courseBox.removeAllItems();
        List<Course> courses = courseService.getCoursesByPage(1, 1000);
        for (Course c : courses) {
            if (semester == null || semester.isEmpty() || c.getSemester().equals(semester)) {
                courseBox.addItem(c);
            }
        }
    }

    private void loadTable() {
        tableModel.setRowCount(0);
        List<Report> reports = reportService.getAllReports();
        for (Report r : reports) {
            Student s = studentService.getStudentById(r.getResno());
            Course c = courseService.getCourseById(r.getRecno());
            Teacher t = teacherService.getTeacherById(r.getRetno());
            tableModel.addRow(new Object[]{
                    r.getResno(), s != null ? s.getSname() : "", r.getRecno(), c != null ? c.getCname() : "", r.getSemester(), r.getGrade(), r.getRetno(), t != null ? t.getTname() : ""
            });
        }
    }

    private void loadTableByStudent() {
        Student s = (Student) studentBox.getSelectedItem();
        if (s == null) return;
        tableModel.setRowCount(0);
        List<Report> reports = reportService.getReportsByStudent(s.getSno());
        for (Report r : reports) {
            Course c = courseService.getCourseById(r.getRecno());
            Teacher t = teacherService.getTeacherById(r.getRetno());
            tableModel.addRow(new Object[]{
                    r.getResno(), s.getSname(), r.getRecno(), c != null ? c.getCname() : "", r.getSemester(), r.getGrade(), r.getRetno(), t != null ? t.getTname() : ""
            });
        }
    }

    private void loadTableByCourse() {
        Course c = (Course) courseBox.getSelectedItem();
        if (c == null) return;
        tableModel.setRowCount(0);
        List<Report> reports = reportService.getReportsByCourse(c.getCno());
        for (Report r : reports) {
            Student s = studentService.getStudentById(r.getResno());
            Teacher t = teacherService.getTeacherById(r.getRetno());
            tableModel.addRow(new Object[]{
                    r.getResno(), s != null ? s.getSname() : "", r.getRecno(), c.getCname(), r.getSemester(), r.getGrade(), r.getRetno(), t != null ? t.getTname() : ""
            });
        }
    }

    private void loadTableByTeacher() {
        Teacher t = (Teacher) teacherBox.getSelectedItem();
        if (t == null) return;
        tableModel.setRowCount(0);
        List<Report> reports = reportService.getReportsByTeacher(t.getTno());
        for (Report r : reports) {
            Student s = studentService.getStudentById(r.getResno());
            Course c = courseService.getCourseById(r.getRecno());
            tableModel.addRow(new Object[]{
                    r.getResno(), s != null ? s.getSname() : "", r.getRecno(), c != null ? c.getCname() : "", r.getSemester(), r.getGrade(), r.getRetno(), t.getTname()
            });
        }
    }

    private void addReportAction() {
        Student s = (Student) studentBox.getSelectedItem();
        Course c = (Course) courseBox.getSelectedItem();
        Teacher t = (Teacher) teacherBox.getSelectedItem();
        String semester = (String) semesterBox.getSelectedItem();
        float grade;
        try {
            grade = Float.parseFloat(gradeField.getText().trim());
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this, "请输入正确的成绩");
            return;
        }
        if (s == null || c == null || t == null || semester == null) {
            JOptionPane.showMessageDialog(this, "请选择所有信息");
            return;
        }
        if (!offerService.isCourseOfferedToClass(c.getCno(), s.getSclno())) {
            JOptionPane.showMessageDialog(this, "该课程未在该学生所在班级开设，无法插入成绩！");
            return;
        }
        Report report = new Report(s.getSno(), c.getCno(), semester, grade, t.getTno());
        boolean success = reportService.addReport(report);
        if (success) {
            JOptionPane.showMessageDialog(this, "添加成功");
            loadTable();
        } else {
            JOptionPane.showMessageDialog(this, "添加失败，可能已存在该成绩记录");
        }
    }

    private void editReportAction() {
        int row = table.getSelectedRow();
        if (row == -1) {
            JOptionPane.showMessageDialog(this, "请先选中一行");
            return;
        }
        String sno = (String) tableModel.getValueAt(row, 0);
        String cno = (String) tableModel.getValueAt(row, 2);
        String semester = (String) tableModel.getValueAt(row, 4);
        String tno = (String) tableModel.getValueAt(row, 6);
        String gradeStr = JOptionPane.showInputDialog(this, "请输入新成绩", tableModel.getValueAt(row, 5));
        if (gradeStr == null) return;
        float grade;
        try {
            grade = Float.parseFloat(gradeStr.trim());
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this, "请输入正确的成绩");
            return;
        }
        Report report = new Report(sno, cno, semester, grade, tno);
        boolean success = reportService.updateReport(report);
        if (success) {
            JOptionPane.showMessageDialog(this, "修改成功");
            loadTable();
        } else {
            JOptionPane.showMessageDialog(this, "修改失败");
        }
    }

    private void deleteReportAction() {
        int row = table.getSelectedRow();
        if (row == -1) {
            JOptionPane.showMessageDialog(this, "请先选中一行");
            return;
        }
        String sno = (String) tableModel.getValueAt(row, 0);
        String cno = (String) tableModel.getValueAt(row, 2);
        int confirm = JOptionPane.showConfirmDialog(this, "确定要删除该成绩记录吗？", "确认删除", JOptionPane.YES_NO_OPTION);
        if (confirm == JOptionPane.YES_OPTION) {
            boolean success = reportService.deleteReport(sno, cno);
            if (success) {
                JOptionPane.showMessageDialog(this, "删除成功");
                loadTable();
            } else {
                JOptionPane.showMessageDialog(this, "删除失败");
            }
        }
    }
} 